;
$(function() {
    var ad = appData(),
        pageNumNow = 1, //当前分页
        tmpObj = {};

    var setting = {
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: false
            },
            key: {
                children: "resourceList"
            }
        },
        callback: {
            beforeClick: beforeClick,
            onCheck: onCheck
        }
    };

    ad.selectList("U_R_TREE", {}, function(data) {
        $.each(data, function(i, n) {
            n.nocheck = true;
           // n.cheked = false;
        })
        $.fn.zTree.init($("#role"), setting, data);
    });

    function beforeClick(treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("role");
        zTree.checkNode(treeNode, !treeNode.checked, null, true);
        return false;
    }

    function onCheck(event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("role");
        var nodes = zTree.getCheckedNodes(true);
        var roleArr = [];
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].getParentNode()) {
                roleArr.push(nodes[i].id);
            }
        }

        sessionStorage.roleArr = JSON.stringify(roleArr);
    }

    showTable(true, 1);

    //角色列表
    function showTable(dontRenderPager, page) {
        var params = {
            page: page, //当前页
            pageSize: appApi("PAGE_SIZE") //每页显示数据条数
        }
        ad.selectList("U_R_LIST", params, function(data) {
            if (data.content.length === 0) {
                $("#roleList").empty().append("<tr><td colspan='6' class='colspanCss'><h1>暂无数据</h1></td></tr>");
                return;
            }

            $("#roleList").empty().append($.tmpl(tmpObj.roleList, data.content));

            $("#roleList td[data-id='9']").parent().find(".icon-trashcan").parent().remove();
            editBtn();

            _as.maxL("#roleList",10);

            if (dontRenderPager) {
                renderPager(data.totalRecord);
            } else if (data.content.length == 0 && data.totalRecord != 0) {
                $("div.page").find("li.active").prev().addClass("active");
                $("div.page").find("li.active:last").remove();
                pageNumNow = pageNumNow - 1;
                if (pageNumNow == 1) {
                    $("div.page").hide();
                }
                showTable(false, pageNumNow);
            } else if (data.content.length == appApi("PAGE_SIZE") && pageNumNow != 1) {
                renderPager(data.totalRecord, pageNumNow - 1);
            } else if (data.totalRecord <= appApi("PAGE_SIZE")) {
                $("div.page").empty();
            }
        });
    }

    //分页
    function renderPager(totalRecord, nowPage) {
        $("div.page").pagination(totalRecord, appApi("PAGE_SIZE"), {
            callback: function(page_id, jq) {
                pageNumNow = page_id + 1;
                showTable(false, pageNumNow);
            }
        }, nowPage);
    }

    function checkTree(id) {
        var zTree = $.fn.zTree.getZTreeObj("role");
        var nodes = zTree.getNodesByParam("id", id, null);
        for (var i = 0; i < nodes.length; i++) {
            zTree.checkNode(nodes[i], !nodes[i].checked, null, true);
            if(nodes[i].getParentNode()) {
                if (!nodes[i].getParentNode().checked) {
                    zTree.checkNode(nodes[i].getParentNode(), true, null, true);
                }
            }
        }
    }

    function editBtn() {
        $(".table tr").on("click", "td:eq(1) a", function() {
            var obj = $(this).parents("tr");
            obj.siblings().removeClass("active").end().addClass('active');
            $("#e1").text("编辑角色").attr("data-id", obj.find("td:eq(0)").data("id"));
            $("#e2").val($(this).text());
            $("#e3").val(obj.find("td:eq(4)").text());
            $(".btnadd").css("display", "inline-block");
            $("#add").hide();
            $("#modify").show();


            resetTree();
            var roleArr = obj.data("resource");
            $.each(roleArr, function(i, n) {
                checkTree(n.id);
            })

        });

        $(".icon-pencil").on("click", function() {
            $(this).parents("tr").find("a").trigger("click");
        });

        $(".btnadd").click(function() {
            $(".table tr").removeClass('active');
            $("#e1").text("添加新角色");
            $(".form-box input").val("");
            $(this).hide();
            $("#add").show();
            $("#modify").hide();
        });

        $(".icon-trashcan").on("click", function() {
            var id = $(this).parents("tr").find("td:eq(0)").data("id"),
                name = $(this).parents("tr").find("td:eq(1)").text();
            _as.jConfirm("<p>确定要删除角色 " + name + " 吗？</p>", function(obj) {
                ad.del("U_R_DELETE", {
                    id: id
                }, function() {
                    showTable(true, 1);
                    $(".btnadd").trigger("click");
                    _as.jAlert("<p>角色删除成功</p>");
                });
            });
        });
    }

    function validate() {
        var onoff = true,
            arr = $.makeArray($(".form-box .fc-danger").parents(".form-item").find("input,textarea").not("input[type='radio']")).reverse();
        $.each(arr, function(index, ele) {
            if (!$(this).val()) {
                $(this).focus();
                onoff = false;
            }
        })
        return onoff;
    }

    function resetTree() {
        var zTree = $.fn.zTree.getZTreeObj("role");
        zTree.checkAllNodes(false);
    }

    Array.prototype.parseList = function(value) {
        var content = [];
        for (var i = 0; i < this.length; i++) {
            content.push(this[i][value]);
        }
        return content.join(",");
    };

    $("#add").on("click", function() {
        if (validate()) {
            var params = {
                name: $("#e2").val(),
                description: $("#e3").val(),
                resourceList: sessionStorage.roleArr ? JSON.parse(sessionStorage.roleArr) : undefined
            };

            ad.insert("U_R_ADD", params, function() {
                showTable(true, 1);
                $(".btnadd").trigger("click");
                resetTree();
                sessionStorage.removeItem("roleArr");
                _as.jAlert("<p>角色添加成功</p>");
            });
        }
    });

    $("#modify").on("click", function() {
        if (validate()) {
            var params = {
                id: $("#e1").attr("data-id"),
                name: $("#e2").val(),
                description: $("#e3").val(),
                resourceList: sessionStorage.roleArr ? JSON.parse(sessionStorage.roleArr) : undefined
            };

            ad.update("U_R_MODIFY", params, function() {
                showTable(true, 1);
                $(".btnadd").trigger("click");
                resetTree();
                sessionStorage.removeItem("roleArr");
                _as.jAlert("<p>角色修改成功</p>");
            });
        }
    });

    (function getTemp() {
        tmpObj.roleList = ["<tr data-resource=\"{{= JSON.stringify(resourceList)}}\">",
"    <td data-id=\"{{= id}}\">{{= num}}</td>",
"    <td><a href=\"javascript:void(0);\">",
"{{= name}}",
"</a></td>",
"    <td>",
"        <span class=\"maxL\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"{{= resourceList.parseList(\'name\')}}\">{{= resourceList.parseList(\'name\')}}</span>",
"    </td>",
"    <td>{{= usernumber}}</td>",
"    <td>{{= description}}</td>",
"    <td>",
"    {{if status == 1}}",
"    <p class=\"table-icons\"><a href=\"javascript:void(0);\"><i class=\"icon-pencil\" title=\"编辑\"></i></a>" +
"<a href=\"javascript:void(0);\"><i class=\"icon-trashcan\" title=\"删除\"></i></a>" +
"</p>",
"    {{else status == 2}}",
"    <span class=\"badge  badge-other\">系统预置</span>",
"    {{/if}} ",
"    </td>",
"</tr>"].join("");
    })();
});